<div class="open-form">
  <div class="open-model">
    <div class="open-auto">
      <table id="infoFormTable"></table>

      <table
        id="orderDetailInventoryFormTable"
        lay-filter="orderDetailInventoryFormTable"
      ></table>
      <button
        class="layui-btn"
        id="addEmptyData"
        style="border-radius: 4px; margin-bottom: 10px"
      >
        添加新捆包号(在明细中选)
      </button>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" id="isCheckFun">
        确认选择
      </button>
      <button
        class="layui-btn layui-btn-primary"
        type="button"
        ew-event="closeDialog"
      >
        关闭
      </button>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="orderDetailInventoryFormTableBar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "upload", "tree", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var admin = layui.admin;
      var config = layui.config;
      const nowData = { ...parentData };
      if (nowData.eventName == "view") {
        $("#addEmptyData").hide();
        $("#isCheckFun").hide();
      }
      var info = nowData.info;
      console.log("info:", nowData);
      //客戶信息
      table.render({
        elem: "#infoFormTable",
        data: info,
        where: {},
        page: false,
        cellMinWidth: 100,
        cols: [
          [
            {
              field: "source",
              title: "数据来源",
              align: "center",
              templet: function (d) {
                return d.source == 1 ? "客户端" : "后台添加";
              },
            },
            { field: "customer", title: "客户代码", align: "center" },
            { field: "orderCode", title: "所属托管订单编号", align: "center" },
            { field: "warehousePrice", title: "托管单价", align: "center" },
            { field: "productCode", title: "客户物料料号", align: "center" },
            { field: "productMaterial", title: "物料类别", align: "center" },
            { field: "productProducer", title: "生产厂家", align: "center" },
            { field: "productBrand", title: "品牌", align: "center" },
            { field: "productMainUnit", title: "单位", align: "center" },
            {
              field: "remainingQuantity",
              title: "剩余发货数量",
              align: "center",
            },
            { field: "quantity", title: "发货数量", align: "center" },
            // , {field: 'weight', title: '单位毛重（kg）', align: 'center'}
            { field: "totalWeight", title: "合计重量", align: "center" },
            // , {field: 'price', title: '小计金额', align: 'center'}
          ],
        ],
        done: function () {
          table.cache["infoFormTable"].forEach((v, i) => {
            if (!v.totalWeight) {
              v.totalWeight = 0;
              v.totalWeight = Number(v.quantity) * Number(v.weight);
              admin.setTableColHtml(
                "infoFormTable",
                i,
                "totalWeight",
                v.totalWeight
              );
            }
          });
        },
      });

      const res = await admin.reqPro(
        "warehouse/warehouse/shipmentOrder/detailList?id=" + nowData.info[0].id
      );
      let listData = res.data;
      if (nowData.info[0].userBundleDetail) {
        listData = [...listData, ...nowData.info[0].userBundleDetail];
      }
      // 需要提交的表的信息
      table.render({
        elem: "#orderDetailInventoryFormTable",
        //   url: config.base + "warehouse/warehouse/shipmentOrder/detailList?id=" + nowData.info[0].id,
        // toolbar: true,
        defaultToolbar: ["filter"],
        data: [...listData],
        where: {},
        // page: true,
        cellMinWidth: 100,
        cols: [
          [
            // {type: 'checkbox', fixed: 'left'}
            { type: "numbers", title: "序号", align: "center" },
            {
              field: "userBundleCode",
              title: "客户捆包号",
              align: "center",
              templet: admin.setTableInput(
                "userBundleCode",
                nowData.eventName === "view",
                "userBundleCode"
              ),
            },
            { field: "sysBundleCode", title: "系统捆包号", align: "center" },
            { field: "productProducer", title: "生产厂家", align: "center" },
            { field: "productVariety", title: "品种", align: "center" },
            { field: "productMark", title: "牌号", align: "center" },
            { field: "productBrand", title: "品牌", align: "center" },
            { field: "productMainUnit", title: "单位", align: "center" },
            {
              field: "netWeight",
              title: "净重(吨)",
              align: "center",
              // templet: admin.setTableInput("netWeight", nowData.eventName === "view", "netWeight")
            },
            {
              field: "grossWeight",
              title: "毛重(吨)",
              align: "center",
              // templet: admin.setTableInput("grossWeight", nowData.eventName === "view", "grossWeight")
            },
            {
              align: "center",
              toolbar: "#orderDetailInventoryFormTableBar",
              title: "操作",
              width: 200,
              fixed: "right",
              hide: nowData.eventName === "view",
            },
          ],
        ],
        done: function () {
          admin.tableInputChangeByClass(
            "orderDetailInventoryFormTable",
            "userBundleCode",
            (index, value, tableData, field, tableId) => {}
          );
          admin.tableInputChangeByClass(
            "orderDetailInventoryFormTable",
            "weight",
            (index, value, tableData, field, tableId) => {}
          );
          // admin.tableInputChange('orderDetailInventoryFormTable');

        },
      });

      table.on("tool(orderDetailInventoryFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["orderDetailInventoryFormTable"].filter(
            (v) => {
              return v["LAY_TABLE_INDEX"] != index;
            }
          );
          table.reload("orderDetailInventoryFormTable", {
            data: list,
          });
        }
      });

      $("#isCheckFun").click(() => {

        var data = table.cache["orderDetailInventoryFormTable"];
        var userBundleCodes = data.map((item) => item.userBundleCode);
        var isExist = false;
        // 判断要添加的商品编码是否存在
        admin.req(
          "warehouse/warehouse/productInventory/queryUserBundleCode",
          JSON.stringify(userBundleCodes),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200 && res.data > 0) {
              layer.msg("商品编码已存在，请重新输入");
              isExist = false;
            } else {
              isExist = true;
            }
          },
          "POST",
          false,
          "application/json;charset=utf-8"
        );
        // debugger;
        // console.log(111,userBundleCodes);

        // $("#isCheckFun").hide();
        if (userBundleCodes.length > data[0].remainingQuantity) {
          // layer.msg("发货数量不能大于库存数量");
          layer.msg("发货数量不能大于库存数量", { icon: 2 });
          return false;
        }
        if (!isExist) {
          return isExist;
        }
        //  ;
        if (typeof parent.layui !== "undefined") {
          childData.list = data.map((v) => {
            v.productDetailId = v.id;
            v.warehousePrice = v.price;
            delete v.id;
            return v;
          });
          console.log("childData", data);
          layer.close(parentData.zindex); // 关闭指定的弹窗
        }
      });

      $("#addEmptyData").click(() => {
        //  ;
        const oldData = table.cache["orderDetailInventoryFormTable"];
        const list = [...oldData, { ...info[0] }];
        table.reload("orderDetailInventoryFormTable", {
          page: {
            limit: Number.MAX_VALUE
            ,curr: 1
          },
          data: list, // 设置新的数据
        });
      });
    }
  );
</script>
